/*******************************************************************************
 * Copyright (c) 2012 March and Conquest.
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************************/
package mrusanov.towers.stats;

import java.io.File;
import java.util.Collections;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GameStatisticsManager {

	private static final String STATS_FILE_NAME = "statistics.xml";

	private static final Logger LOG = LoggerFactory.getLogger(GameStatisticsManager.class);

	private GameStatisticsManager() {
		throw new UnsupportedOperationException();
	}

	public static List<PlayersPair> retreivePairResults() {
		File file = new File(STATS_FILE_NAME);
		if (!file.exists()) {
			return Collections.emptyList();
		}

		try {
			JAXBContext context = JAXBContext.newInstance(GameStatisticsList.class);
			Unmarshaller unmarshaller = context.createUnmarshaller();
			GameStatisticsList list = (GameStatisticsList) unmarshaller.unmarshal(file);
			return list.buildPlayersPairResultsList();
		} catch (Exception ex) {
			LOG.error(ex.getMessage(), ex);
			return Collections.emptyList();
		}
	}

	public static void addGameResult(GameStatistics gameStatistics) {
		try {
			JAXBContext context = JAXBContext.newInstance(GameStatisticsList.class);
			GameStatisticsList list;

			File file = new File(STATS_FILE_NAME);
			if (file.exists()) {
				Unmarshaller unmarshaller = context.createUnmarshaller();
				list = (GameStatisticsList) unmarshaller.unmarshal(file);
			} else {
				file.createNewFile();
				list = new GameStatisticsList();
			}

			list.getStats().add(gameStatistics);
			Marshaller marshaller = context.createMarshaller();
			marshaller.marshal(list, file);
		} catch (Exception ex) {
			LOG.error(ex.getMessage(), ex);
		}
	}
}
